
import { ElMessage } from "element-plus";
import router from "./router";

import { useUserStore } from "./stores/userStore"
import { getProfileAPI } from "./apis/user";
import { asyncRoutes } from "./router/asyncRouter";
import type { RouteRecordRaw } from "vue-router";
import { useMenuStore } from "./stores/menu";

const WHITE_LIST = ['/login','/404']
// 筛选一级路由
const getFirstRoutePerms = (permissions:string[])=>{
  const res = permissions.map(item=>item.split(':')[0])
  return Array.from(new Set(res))
}

// 筛选二级路由
const getSecondRoutePerms = (permissions:string[])=>{
  const res = permissions.map(item=>{
    return `${item.split(':')[0]}:${item.split(':')[1]}`
  })
  return Array.from(new Set(res))
}

// 根据权限生成路由
const createAsyncRoutes = (firstRoutePerms:string[],secondRoutePerms:string[])=>{
  if (firstRoutePerms.includes("*")) {
    // 管理员（拷贝 - 防止重复登录同一个用户时，此变量值返回给外面后不断 push * 地址，导致左侧菜单 key 重复报错问题）
    return [...asyncRoutes];
  }
  // 筛选一级路由
  const firstRoute = asyncRoutes.filter(item=>firstRoutePerms.includes(item.meta?.permission as string))
  // 筛选动态路由
  const secondRoute = firstRoute.map(item=>{
    return {
      ...item,
      children:item.children?.filter(child=>secondRoutePerms.includes(child.meta?.permission as string))
    }
  })

  return secondRoute
}


router.beforeEach(async(to, from, next) => {
  const userStore = useUserStore()
  if(userStore.token){
    // 获取登录人信息
    if(!userStore.profile.id){
      const res = await getProfileAPI()
      console.log('res',res)
      userStore.setProfile(res.data)
      const firstRoutePerms = getFirstRoutePerms(res.data.permissions)
      console.log('firstRoutePerms',firstRoutePerms)
      const secondRoutePerms = getSecondRoutePerms(res.data.permissions)
      console.log('secondRoutePerms',secondRoutePerms)
      // 根据权限生成路由
      const asyncRoutes = createAsyncRoutes(firstRoutePerms,secondRoutePerms)
      // 2. 遍历匹配的路由，动态添加到路由表中
      asyncRoutes.forEach(route=>{
        router.addRoute(route as RouteRecordRaw)
      })
      // 3. 动态添加到菜单中
      const menuStore = useMenuStore()
      menuStore.setMenuList(asyncRoutes as RouteRecordRaw[])
      // 
      next({...to})
    }
    
    next()
  }else{
    if(WHITE_LIST.includes(to.path)){
      next()
    }else{
      next('/login')
      ElMessage.warning("身份信息失效，请先登录")
    }
  }
})